package com.retail.task;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.retail.core.entity.enums.DelFlagEnum;
import com.retail.core.entity.enums.StatusFlagEnum;
import com.retail.core.task.RetailQuartzJobBean;
import com.retail.msg.entity.request.RetailMsgRequest;
import com.retail.msg.enums.MsgTypeEnums;
import com.retail.msg.service.RetailMsgService;
import com.retail.order.entity.request.RetailSettleOrderRequest;
import com.retail.order.entity.vo.RetailSettleOrderVo;
import com.retail.order.enums.OrderStatusEnums;
import com.retail.order.service.RetailSettleOrderService;
import com.retail.shop.entity.vo.RetailShopVo;
import com.retail.shop.enums.ShopSourceEnums;
import com.retail.shop.service.RetailShopService;
import com.retail.system.entity.vo.AdminVo;
import com.retail.system.service.AdminService;
import com.retail.system.service.CronTriggersService;
import com.retail.system.service.CronTriggersSynchroTimeService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 抖音shop
 *
 * @author Administrator
 */
@Component
@Slf4j
public class DouyinOrderJobTask extends RetailQuartzJobBean {
    @Autowired
    private CronTriggersService cronTriggersService;

    @Autowired
    private CronTriggersSynchroTimeService cronTriggersSynchroTimeService;

    @Autowired
    private RetailSettleOrderService retailSettleOrderService;

    @Autowired
    private RetailMsgService retailMsgService;

    @Autowired
    private RetailShopService retailShopService;

    @Autowired
    private AdminService adminService;

    @Override
    protected CronTriggersService getCronTriggersService() {
        return cronTriggersService;
    }

    @Override
    protected CronTriggersSynchroTimeService getcronTriggersSynchroTimeService() {
        return cronTriggersSynchroTimeService;
    }

    @Override
    public void task(JobExecutionContext jobExecutionContext) {
        new Thread(() -> {
            Date startTime = new Date();
            List<RetailShopVo> allShops = retailShopService.findAllShopByShopSource(ShopSourceEnums.DY_TYPE.getValue());
//        while (startTime.getTime() < DateUtil.date().getTime()) {
            String billDate = DateUtil.format(startTime, "yyyy-MM-dd");
            List<RetailSettleOrderRequest> orders = retailSettleOrderService.syncTokTikOrderList(billDate, allShops);
            if (orders.size() > 0) {
                operaOrder(orders);
            }
        }).start();
//        Date startTime = DateUtil.parse("2024-06-01");
    }

    /**
     * 处理商户数据
     *
     * @param orders 订单s
     */
    private void operaOrder(List<RetailSettleOrderRequest> orders) {
        orders.forEach(orderRequest -> {
            try {
                String orderId = orderRequest.getOrderId();
                RetailSettleOrderVo retailSettleOrderVo = retailSettleOrderService.getModelByOrderIdAndSource(orderId, ShopSourceEnums.DY_TYPE.getValue());
                if (ObjectUtil.isEmpty(retailSettleOrderVo)) {
//                orderRequest.setId(retailSettleOrderVo.getId());
//                if (ObjectUtil.equal(orderRequest.getOrderStatus(), OrderStatusEnums.ORDERSTATUS_FINISH.getValue()) && ObjectUtil.isEmpty(retailSettleOrderVo.getVerifyTime())) {
//                    retailSettleOrderVo.setVerifyTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
//                }
//                retailSettleOrderService.update(orderRequest);
                    retailSettleOrderService.save(orderRequest);
                    insertOrderMsg(orderRequest);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

//            if (ObjectUtil.isEmpty(retailSettleOrderVo) || ObjectUtil.notEqual(orderRequest.orderHashMd5(), retailSettleOrderVo.orderHashMd5())) {
//                insertOrderMsg(orderRequest);
//            }
        });
    }

    public static void main(String[] args) {
//        Date startTime = DateUtil.parse("2024-06-01");
//        System.out.println(startTime);
//        String sS = DateUtil.format(startTime, "yyyy-MM-dd");
//        System.out.println(sS);
//        Date end= DateUtil.offset(startTime, DateField.DAY_OF_YEAR, 1);
//        System.out.println(end);
//        System.out.println(DateUtil.format(end, "yyyy-MM-dd"));
//
//        System.out.println(DateUtil.now());


//        1722488375
//        1724514594820
//        1722488375
        Date date = DateUtil.date(1722488375L * 1000);
        System.out.println(System.currentTimeMillis());
        System.out.println(date);
    }


    /**
     * 插入订单推送信息
     *
     * @param shop
     */
    private void insertOrderMsg(RetailSettleOrderRequest shop) {
        // 插入记录数据
        RetailMsgRequest request = new RetailMsgRequest();
        request.setMsgType(MsgTypeEnums.ORDER_MSG.getValue());
        JSONObject jsonObject = new JSONObject();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("订单来源：抖音订单," + "订单编号：" + shop.getOrderId() + ",");
        stringBuffer.append("订单金额：" + shop.getReceiptAmount() + ",");
        stringBuffer.append("订单时间：" + shop.getPayTime() + ",");
        stringBuffer.append("当前状态为：" + OrderStatusEnums.getStatusValues(shop.getOrderStatus()));
        request.setMsgContent(stringBuffer.toString());
        jsonObject.put("orderId", shop.getOrderId());
        jsonObject.put("orderSource", "抖音订单");
        jsonObject.put("orderTime", shop.getPayTime());
        jsonObject.put("orderStatus", shop.getOrderStatus());
        jsonObject.put("orderStatusName", OrderStatusEnums.getStatusValues(shop.getOrderStatus()));
        jsonObject.put("orderPay", shop.getReceiptAmount());
        jsonObject.put("orderName", shop.getProductName());
        AdminVo adminVo = adminService.getModelByPoiId(shop.getPoiId());
        RetailShopVo retailShopVo = retailShopService.getModelByPoiIdLimmit1(shop.getPoiId());
        Set<String> msgUser = new HashSet<>();
        if (ObjectUtil.isNotEmpty(adminVo)) {
            msgUser.add(adminVo.getId() + "");
        }
        if (ObjectUtil.isNotEmpty(retailShopVo)) {
            msgUser.add(retailShopVo.getOwnerId() + "");
        }

        request.setMsgUser(msgUser.stream().collect(Collectors.joining(",")));
//        request.setMsgUser("31,33,39,54,55,56,");
        request.setMsgJson(jsonObject.toJSONString());
        request.setDelFlag(DelFlagEnum.NO.getValue());
        request.setStatusFlag(StatusFlagEnum.USE.getValue());
        request.setCreateUser(1L);
        request.setRemark("订单推送");
        if (ObjectUtil.isNotEmpty(msgUser) && msgUser.size() > 0) {
            Long id = retailMsgService.save(request);
            retailMsgService.delayMsg(id);
        }
    }
}
